package com.zadtek.shopmall.fragments;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.zadtek.shopmall.Event.EventPoiAddress;
import com.zadtek.shopmall.R;
import com.zadtek.shopmall.activities.ChoosePoiAddressActivity;
import com.zadtek.shopmall.activities.SearchActivity;
import com.zadtek.shopmall.adapter.HomeAdapter;
import com.zadtek.shopmall.adapter.MyAdapter;
import com.zadtek.shopmall.base.AbsFragment;
import com.zadtek.shopmall.base.BaseActivity;
import com.zadtek.shopmall.bean.GetBoundsResponse;
import com.zadtek.shopmall.bean.HomeBaseBean;
import com.zadtek.shopmall.bean.HomeBean;
import com.zadtek.shopmall.bean.HomeBean2;
import com.zadtek.shopmall.bean.HomeShopBean;
import com.zadtek.shopmall.bean.HotNewsItem;
import com.zadtek.shopmall.bean.IndexProductItem;
import com.zadtek.shopmall.bean.MultiItem;
import com.zadtek.shopmall.bean.PictureItem;
import com.zadtek.shopmall.bean.RedPacketBean;
import com.zadtek.shopmall.bean.SpikeItem;
import com.zadtek.shopmall.bean.TypeBean;
import com.zadtek.shopmall.net.BaseObserver;
import com.zadtek.shopmall.net.BaseResponse;
import com.zadtek.shopmall.net.NetTool;
import com.zadtek.shopmall.other.Const;
import com.zadtek.shopmall.other.DialogManger;
import com.zadtek.shopmall.other.LocationManger;
import com.zadtek.shopmall.utils.LogUtil;
import com.zadtek.shopmall.utils.Screenutils;
import com.zadtek.shopmall.utils.ToastUtil;
import com.zadtek.shopmall.view.AniManager;
import com.zadtek.shopmall.view.GridSpacingItemDecoration;
import com.zadtek.shopmall.view.NoScrollView;
import com.zadtek.shopmall.view.SwitcherView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cn.iwgang.countdownview.CountdownView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

import static com.zadtek.shopmall.other.Const.jumpHandle;

public class HomeFragment extends AbsFragment implements View.OnClickListener {
    private static final String TAG = "HomeFragment";
    private TextView leftText;
    private ImageView rightIcon;
    private RecyclerView recyclerView;
    private Banner banner, banner2, banner3;
    private ImageView ivAdHeader, ivAdImage1, ivAdImage2, ivAdImage3;
    private NoScrollView noScroll;
    private ImageView rt, lt, rb, lb;
    private LinearLayout spikeContainer, bar, adviceShopContainer;
    private View headerView;
    private SwitcherView rollingTextView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private CountdownView countdownView;
    private EditText etSearch;
    private int showLoadingCount = 0;
    private HomeAdapter homeAdapter;
    private MyAdapter noScrollAdapter;
    private List<MultiItem> mData = new LinkedList<>();
    private ImageView car;
    private List<PictureItem> bannerList = new LinkedList<>();
    private List<PictureItem> bannerList2 = new LinkedList<>();
    private List<PictureItem> bannerList3 = new LinkedList<>();
    private List<HotNewsItem> newsList = new LinkedList<>();
    private ArrayList<TypeBean> typeBeans = new ArrayList<>();
    private List<PictureItem> gridAd4 = new LinkedList<>();
    private List<SpikeItem> spikeItems = new LinkedList<>();
    private List<PictureItem> adviceShopItems = new LinkedList<>();
    private List<HomeShopBean> nearbyShopItems = new LinkedList<>();
    private List<IndexProductItem> indexProductItems = new LinkedList<>();

    private HomeBean homeBean;
    private CountDownTimer countDownTimer;
    private TextView tvMoreNews;
    private Badge carNum;
    private int carnum = 0;

    @Override
    public int setView() {
        return R.layout.fragment_home;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initView();
        setLogic();
        requestDataTemp();
        requestData();
        updateView();
        checkRed();

    }

    private void updateView() {
        List<String> list = new LinkedList<>();
        for (PictureItem i : homeBean.getBannerList()) {
            list.add(i.getUrl());
        }
        banner.setImages(list);
        banner.start();
        banner2.setImages(list);
        banner2.start();
        banner3.setImages(list);
        banner3.start();

        typeBeans.addAll(homeBean.getTypeBeans());

        noScrollAdapter.notifyDataSetChanged();

        ArrayList<String> mScrollText = new ArrayList<>();
        for (HotNewsItem newsItem1 : homeBean.getNewsList()) {
            mScrollText.add(newsItem1.getTitle());
        }

        rollingTextView.setResource(mScrollText);
        rollingTextView.startRolling();

        Glide.with(mActivity).load(homeBean.getGridAd4().get(1).getUrl()).into(lt);
        Glide.with(mActivity).load(homeBean.getGridAd4().get(1).getUrl()).into(rt);
        Glide.with(mActivity).load(homeBean.getGridAd4().get(1).getUrl()).into(lb);
        Glide.with(mActivity).load(homeBean.getGridAd4().get(1).getUrl()).into(rb);

        addViewToSpikeContainer();
        addViewToIndexShopContainer();

        nearbyShopItems.addAll(homeBean.getNearbyShopItems());
        for (HomeShopBean bean : nearbyShopItems) {
            mData.add(new MultiItem(MultiItem.Type_Home_Shop, bean));
        }

        indexProductItems.addAll(homeBean.getIndexProductItems());

        mData.add(new MultiItem(MultiItem.Type_Home_Header, ""));
        for (IndexProductItem indexProductItem1 : indexProductItems) {
            mData.add(new MultiItem(MultiItem.Type_Product, indexProductItem1));
        }
        homeAdapter.notifyDataSetChanged();
    }

    private float latitude = 0.0f;
    private float longitude = 0.0f;

    private void requestDataTemp() {

        mActivity.performCodeWithPermission("需要定位权限", new BaseActivity.PermissionCallback() {
            @Override
            public void hasPermission() {
                LocationManger.fetch(new LocationManger.OnLocationListener() {
                    @Override
                    public void onLocation(AMapLocation location) {
                        latitude = (float) location.getLatitude();
                        longitude = (float) location.getLongitude();

                        String city = "";
                        if (location.getErrorCode() == 0) {
                            leftText.setText(location.getCity() + location.getDistrict() + location.getStreet() + location.getAoiName());
                            city = city + location.getCity();
                        } else {
                            leftText.setText("未知");
                            ToastUtil.showToast(location.getErrorInfo()+"ypk");
                        }
                        requestNearBy(city);
                        dismissLoadingProgress();
                    }
                });
            }

            @Override
            public void noPermission() {

            }
        }, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION});


       /* Log.i(TAG, "requestDataTemp: " + Const.userid + " " + Const.token);
        Map<String, Object> params = NetTool.newParams();
        params.put("lat", latitude);
        params.put("lat", longitude);
        NetTool.getApi().getHomeData2(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<HomeBean2>>(this) {
                    @Override
                    public void onData(BaseResponse<HomeBean2> value) {
                        Log.i(TAG, "onData: value" + value.code + value.msg);
                        //homeBean = value.getData();
                        //updateView();
                    }
                });
*/

        showLoadingProgress();
    }

    private void requestNearBy(String city) {
        Map<String, Object> params = NetTool.newParams();
        NetTool.getApi()
                .getNearByShop(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<List<HomeShopBean>>>(this) {
                    @Override
                    public void onData(BaseResponse<List<HomeShopBean>> value) {
                        Log.i(TAG, "requestNearBy onData: msg=" + value.msg + " getCode=" + value.getCode());
                        if (value.getCode() == 0 && value.getData() != null) {
                            nearbyShopItems.clear();
                            nearbyShopItems.addAll(value.getData());
                            updateNearByShop();
                        }
                    }
                });
    }

    private void updateNearByShop() {
        mData.clear();
        for (HomeShopBean bean : nearbyShopItems) {
            mData.add(new MultiItem(MultiItem.Type_Home_Shop, bean));
        }
        mData.add(new MultiItem(MultiItem.Type_Home_Header, ""));
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(mData.size() + 1, 2, getResources().getDimensionPixelSize(R.dimen.mini_margin), false));
        IndexProductItem indexProductItem = new IndexProductItem();
        indexProductItem.setProductImgUrl("http://tc.zadtek.com/aaa/images/201603/thumb_img/531_thumb_G_1457132885920.jpg");
        indexProductItem.setProductPrice("￥90.00");
        indexProductItem.setProductTitle("申士（SNSIR）SN系 家庭影院套装 5.1组合功放音响 回音壁挂电视音箱 铝合金黑色");
        indexProductItem.setProductSales("销量 999");
        indexProductItem.setProductStock("库存 999");
        indexProductItem.setType(Const.PRODUCT);
        indexProductItem.setId(454353);

        IndexProductItem indexProductItem2 = new IndexProductItem();
        indexProductItem2.setProductImgUrl("http://tc.zadtek.com/aaa/images/201603/thumb_img/528_thumb_G_1457132421645.jpg");
        indexProductItem2.setProductPrice("4000.00");
        indexProductItem2.setProductTitle("佳仁按摩椅 JR-Q3豪华3D家用按摩椅 旗舰款(贵族红)");
        indexProductItem2.setProductSales("销量 999");
        indexProductItem2.setProductStock("库存 999");
        indexProductItem2.setType(Const.PRODUCT);
        indexProductItem2.setId(4354644);
        indexProductItems.clear();
        indexProductItems.add(indexProductItem);
        indexProductItems.add(indexProductItem2);
        indexProductItems.add(indexProductItem);
        indexProductItems.add(indexProductItem2);
        indexProductItems.add(indexProductItem);
        indexProductItems.add(indexProductItem2);
        indexProductItems.add(indexProductItem);
        indexProductItems.add(indexProductItem2);
        for (IndexProductItem indexProductItem1 : indexProductItems) {
            mData.add(new MultiItem(MultiItem.Type_Product, indexProductItem1));
        }
        homeAdapter.notifyDataSetChanged();
    }

    private void setLogic() {
        leftText.setOnClickListener(this);
        rightIcon.setOnClickListener(this);
        rt.setOnClickListener(this);
        lt.setOnClickListener(this);
        rb.setOnClickListener(this);
        lb.setOnClickListener(this);
        etSearch.setFocusable(false);
        tvMoreNews.setOnClickListener(this);
        etSearch.setOnClickListener(this);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                //bannerList.get(position).getLink();
                jumpHandle(mActivity, homeBean.getBannerList().get(position));
            }
        });
        rollingTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //HotNewsItem item = newsList.get(rollingTextView.getCurrentIndex());
                jumpHandle(mActivity, homeBean.getNewsList().get(rollingTextView.getCurrentIndex()));
            }
        });


        noScrollAdapter = new MyAdapter<TypeBean>(typeBeans, R.layout.type_item) {
            @Override
            public void bindView(final ViewHolder holder, TypeBean obj) {
                holder.getItemView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int position = holder.getItemPosition();
                        jumpHandle(mActivity, typeBeans.get(position));
                    }
                });
                Glide.with(mActivity).load(obj.getIconUrl()).into((ImageView) holder.getView(R.id.img));
                holder.setText(R.id.text, obj.getTypeName());
            }
        };
        noScroll.setAdapter(noScrollAdapter);
        homeAdapter = new HomeAdapter(mActivity, mData);
        homeAdapter.addHeaderView(headerView);
        recyclerView.setAdapter(homeAdapter);
        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int position = layoutManager.findFirstVisibleItemPosition();
                if (position == 0) {
                    View firstVisiableChildView = layoutManager.findViewByPosition(position);
                    int bannerheight = banner.getHeight();
                    int top = firstVisiableChildView.getTop();
                    if (top + bannerheight > 0) {
                        bar.setBackgroundColor(mActivity.getResources().getColor(R.color.transparent));
                        leftText.setBackground((mActivity.getResources().getDrawable(R.drawable.location_bk_transparent)));
                        leftText.setTextColor(mActivity.getResources().getColor(R.color.color_white));
                        Drawable drawable3 = mActivity.getResources().getDrawable(R.drawable.address_mini_white);
                        Drawable drawable2 = mActivity.getResources().getDrawable(R.drawable.rightarrow_mini);
                        drawable3.setBounds(0, 0, drawable3.getIntrinsicWidth(), drawable3.getIntrinsicHeight());
                        drawable2.setBounds(0, 0, drawable2.getIntrinsicWidth(), drawable2.getIntrinsicHeight());
                        leftText.setCompoundDrawables(drawable3, null, drawable2, null);
                        //rightIcon.setImageDrawable(mActivity.getResources().getDrawable(R.drawable.ic_notifications_white));
                        etSearch.setBackground((mActivity.getResources().getDrawable(R.drawable.search_bk_transparent)));
                        etSearch.setHintTextColor(mActivity.getResources().getColor(R.color.color_text_black));
                        etSearch.setTextColor(mActivity.getResources().getColor(R.color.color_text_black));
                        Drawable drawable = mActivity.getResources().getDrawable(R.drawable.ic_search);
                        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                        etSearch.setCompoundDrawables(drawable, null, null, null);
                    } else {
                        bar.setBackgroundColor(mActivity.getResources().getColor(R.color.color_grey));
                        leftText.setBackground((mActivity.getResources().getDrawable(R.drawable.location_bk)));
                        leftText.setTextColor(mActivity.getResources().getColor(R.color.color_white));
                        Drawable drawable3 = mActivity.getResources().getDrawable(R.drawable.address_mini_white);
                        Drawable drawable2 = mActivity.getResources().getDrawable(R.drawable.rightarrow_mini);
                        drawable3.setBounds(0, 0, drawable3.getIntrinsicWidth(), drawable3.getIntrinsicHeight());
                        drawable2.setBounds(0, 0, drawable2.getIntrinsicWidth(), drawable2.getIntrinsicHeight());
                        leftText.setCompoundDrawables(drawable3, null, drawable2, null);
                        //rightIcon.setImageDrawable(mActivity.getResources().getDrawable(R.drawable.ic_notifications));
                        etSearch.setBackground((mActivity.getResources().getDrawable(R.drawable.search_bk)));
                        etSearch.setHintTextColor(mActivity.getResources().getColor(R.color.color_text_black));
                        etSearch.setTextColor(mActivity.getResources().getColor(R.color.color_text_black));
                        Drawable drawable = mActivity.getResources().getDrawable(R.drawable.ic_search);
                        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                        etSearch.setCompoundDrawables(drawable, null, null, null);
                    }
                }
            }
        });
        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ToastUtil.showToast(mData.get(position).getItemType() + "itemclick" + position);
                HomeBaseBean homeBaseBean = (HomeBaseBean) mData.get(position).getData();
                jumpHandle(mActivity, homeBaseBean);

            }
        });
        homeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.iv_add_to_car) {
                    startAnim((View) view.getParent().getParent(), view);
                }
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestDataTemp();
                swipeRefreshLayout.setRefreshing(false);
            }
        });

    }

    private void requestData() {
        homeBean = new HomeBean();
        PictureItem item = new PictureItem();
        item.setUrl("http://tc.zadtek.com/aaa/data/gallery_album/original_img/58db8addb5737.jpg");
        item.setLink("");
        item.setType(Const.PRODUCT);
        item.setId(1);
        bannerList.add(item);
        bannerList2.add(item);
        bannerList3.add(item);
        PictureItem picitem2 = new PictureItem();
        picitem2.setUrl("http://tc.zadtek.com/aaa/data/gallery_album/original_img/58c11d8c63e09.jpg");
        picitem2.setLink("");
        picitem2.setType(Const.SHOP);
        picitem2.setId(2);
        bannerList.add(picitem2);
        bannerList2.add(item);
        bannerList3.add(item);


        homeBean.setBannerList(bannerList);
        homeBean.setBannerList(bannerList2);
        homeBean.setBannerList(bannerList3);

        TypeBean typeBean = new TypeBean();
        typeBean.setTypeName("店铺街");
        typeBean.setIconUrl("http://tc.zadtek.com/aaa/data/gallery_album/original_img/58db8a08bbc12.png");
        typeBean.setType(Const.SHOP_LIST);

        TypeBean typeBean2 = new TypeBean();
        typeBean2.setTypeName("品牌街");
        typeBean2.setIconUrl("http://tc.zadtek.com/aaa/data/gallery_album/original_img/58db8a089cfdb.png");
        typeBean2.setType(Const.PRODUCT_LIST);

        TypeBean typeBean3 = new TypeBean();
        typeBean3.setTypeName("万能跑腿");
        typeBean3.setIconUrl("http://tc.zadtek.com/aaa/data/gallery_album/original_img/58db8a089cfdb.png");
        typeBean3.setType(Const.TASK);
        TypeBean typeBean4 = new TypeBean();
        typeBean4.setTypeName("顺风车");
        typeBean4.setIconUrl("http://tc.zadtek.com/aaa/data/gallery_album/original_img/58db8a089cfdb.png");
        typeBean4.setType(Const.CAR);
        typeBeans.add(typeBean);
        typeBeans.add(typeBean2);
        typeBeans.add(typeBean);
        typeBeans.add(typeBean3);
        typeBeans.add(typeBean4);
        typeBeans.add(typeBean2);
        homeBean.setTypeBeans(typeBeans);

        HotNewsItem newsItem = new HotNewsItem();
        newsItem.setTitle("诺基亚6681广告欣赏！");
        newsItem.setLink("");
        newsItem.setType(Const.NEWS);

        newsList.add(newsItem);
        newsList.add(newsItem);
        newsList.add(newsItem);
        newsList.add(newsItem);
        homeBean.setNewsList(newsList);

        PictureItem p1 = new PictureItem();
        p1.setUrl("http://tc.zadtek.com/aaa/data/gallery_album/original_img/58db45c1b998e.jpg");
        p1.setLink("");
        p1.setType(Const.PRODUCT_LIST);
        p1.setId(3);
        gridAd4.add(p1);
        gridAd4.add(p1);
        gridAd4.add(p1);
        gridAd4.add(p1);
        homeBean.setGridAd4(gridAd4);

        SpikeItem spikeItem = new SpikeItem();
        spikeItem.setPrice("22.00");
        spikeItem.setOldPrice("88.00");
        spikeItem.setType(Const.PRODUCT);
        spikeItem.setProductImgUrl("http://tc.zadtek.com/aaa/images/201512/thumb_img/148_thumb_G_1450313404816.jpg");
        spikeItem.setId(543);
        spikeItems.add(spikeItem);
        spikeItems.add(spikeItem);
        spikeItems.add(spikeItem);
        spikeItems.add(spikeItem);
        spikeItems.add(spikeItem);
        spikeItems.add(spikeItem);
        spikeItems.add(spikeItem);

        homeBean.setSpikeItems(spikeItems);
        homeBean.setSpikerestTime(888);

        PictureItem pictureItem = new PictureItem();
        adviceShopItems.add(pictureItem);
        adviceShopItems.add(pictureItem);
        adviceShopItems.add(pictureItem);
        adviceShopItems.add(pictureItem);
        homeBean.setAdviceShopItem(adviceShopItems);

        IndexProductItem indexProductItem = new IndexProductItem();
        indexProductItem.setProductImgUrl("http://tc.zadtek.com/aaa/images/201603/thumb_img/531_thumb_G_1457132885920.jpg");
        indexProductItem.setProductPrice("￥90.00");
        indexProductItem.setProductTitle("申士（SNSIR）SN系 家庭影院套装 5.1组合功放音响 回音壁挂电视音箱 铝合金黑色");
        indexProductItem.setProductSales("销量 999");
        indexProductItem.setProductStock("库存 999");
        indexProductItem.setType(Const.PRODUCT);
        indexProductItem.setId(454353);

        IndexProductItem indexProductItem2 = new IndexProductItem();
        indexProductItem2.setProductImgUrl("http://tc.zadtek.com/aaa/images/201603/thumb_img/528_thumb_G_1457132421645.jpg");
        indexProductItem2.setProductPrice("4000.00");
        indexProductItem2.setProductTitle("佳仁按摩椅 JR-Q3豪华3D家用按摩椅 旗舰款(贵族红)");
        indexProductItem2.setProductSales("销量 999");
        indexProductItem2.setProductStock("库存 999");
        indexProductItem2.setType(Const.PRODUCT);
        indexProductItem2.setId(4354644);

        indexProductItems.add(indexProductItem);
        indexProductItems.add(indexProductItem2);
        indexProductItems.add(indexProductItem);
        indexProductItems.add(indexProductItem2);
        indexProductItems.add(indexProductItem);
        homeBean.setIndexProductItems(indexProductItems);

        HomeShopBean homeShopBean = new HomeShopBean();
        homeShopBean.setType(Const.SHOP);
        nearbyShopItems.add(homeShopBean);
        nearbyShopItems.add(homeShopBean);
        nearbyShopItems.add(homeShopBean);
        nearbyShopItems.add(homeShopBean);
        homeBean.setNearbyShopItems(nearbyShopItems);

    }

    private void initView() {
        leftText = (TextView) findViewById(R.id.left_text);
        rightIcon = (ImageView) findViewById(R.id.right_icon);
        recyclerView = (RecyclerView) findViewById(R.id.recycleview);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mActivity, 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        etSearch = (EditText) findViewById(R.id.search_edit);
        bar = (LinearLayout) findViewById(R.id.search_bar);
        headerView = getHeaderView();
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefreshlayout);
        car = (ImageView) findViewById(R.id.car);
        carNum = new QBadgeView(mActivity).bindTarget(car);


        car.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("HomeFragment.onClick");

            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_text:
                startActivity(new Intent(mActivity, ChoosePoiAddressActivity.class));
                break;
            case R.id.right_icon:
                List<RedPacketBean> data = new LinkedList<>();
                data.add(new RedPacketBean());
                data.add(new RedPacketBean());
                data.add(new RedPacketBean());
                data.add(new RedPacketBean());
                data.add(new RedPacketBean());
                data.add(new RedPacketBean());
                break;
            case R.id.lt:
                jumpHandle(mActivity, homeBean.getGridAd4().get(0));
                break;
            case R.id.rt:
                jumpHandle(mActivity, homeBean.getGridAd4().get(1));
                break;
            case R.id.rb:
                jumpHandle(mActivity, homeBean.getGridAd4().get(2));
                break;
            case R.id.lb:
                jumpHandle(mActivity, homeBean.getGridAd4().get(3));
                break;
            case R.id.search_edit:
                startActivity(new Intent(mActivity, SearchActivity.class));
                break;
            case R.id.tv_more_news:
                ToastUtil.showToast("更多新闻！");
                break;
        }
    }

    private View getHeaderView() {
        View v = getLayoutInflater().inflate(R.layout.home_header, (ViewGroup) recyclerView.getParent(), false);
        banner = (Banner) v.findViewById(R.id.banner);
        banner2 = (Banner) v.findViewById(R.id.banner2);
        banner3 = (Banner) v.findViewById(R.id.banner3);
        noScroll = (NoScrollView) v.findViewById(R.id.grid_container);
        rt = (ImageView) v.findViewById(R.id.rt);
        lt = (ImageView) v.findViewById(R.id.lt);
        rb = (ImageView) v.findViewById(R.id.rb);
        lb = (ImageView) v.findViewById(R.id.lb);
        ivAdHeader = (ImageView) v.findViewById(R.id.iv_ad_header);
        ivAdImage1 = (ImageView) v.findViewById(R.id.iv_ad_img1);
        ivAdImage2 = (ImageView) v.findViewById(R.id.iv_ad_img2);
        ivAdImage3 = (ImageView) v.findViewById(R.id.iv_ad_img3);
        tvMoreNews = (TextView) v.findViewById(R.id.tv_more_news);
        spikeContainer = (LinearLayout) v.findViewById(R.id.spike_container);
        adviceShopContainer = (LinearLayout) v.findViewById(R.id.advice_shop_container);
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setImageLoader(new GlideImageLoader());
        banner2.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner2.setIndicatorGravity(BannerConfig.CENTER);
        banner2.setImageLoader(new GlideImageLoader());
        banner3.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner3.setIndicatorGravity(BannerConfig.CENTER);
        banner3.setImageLoader(new GlideImageLoader());
        rollingTextView = (SwitcherView) v.findViewById(R.id.scroll_text);
        countdownView = (CountdownView) v.findViewById(R.id.countdown);

        return v;
    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(context).load(path).into(imageView);
        }
    }

    private void addViewToSpikeContainer() {
        //countdownView.start(homeBean.getSpikerestTime());
        countDownTimer = new CountDownTimer(homeBean.getSpikerestTime() * 1000, 1000) {
            @Override
            public void onTick(long l) {
                if (countdownView != null) {
                    countdownView.updateShow(l);
                }
            }

            @Override
            public void onFinish() {
                if (countdownView != null) {
                    countdownView.allShowZero();
                }
            }
        };
        countDownTimer.start();
        for (int i = 0; i < homeBean.getSpikeItems().size(); i++) {
            View v = getLayoutInflater().inflate(R.layout.spike_item, null);
            TextView price = (TextView) v.findViewById(R.id.price);
            TextView oldPrice = (TextView) v.findViewById(R.id.old_price);
            ImageView imageView = (ImageView) v.findViewById(R.id.img);
            Glide.with(mActivity).load(homeBean.getSpikeItems().get(i).getProductImgUrl()).into(imageView);
            oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            price.setText(homeBean.getSpikeItems().get(i).getPrice());
            oldPrice.setText(homeBean.getSpikeItems().get(i).getOldPrice());
            final int finalI = i;
            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    jumpHandle(mActivity, homeBean.getSpikeItems().get(finalI));
                }
            });
            spikeContainer.addView(v);
        }
    }

    ;

    private void addViewToIndexShopContainer() {
        ImageView imageView = new ImageView(mActivity);
        ViewGroup.LayoutParams layoutParams = new LinearLayout.LayoutParams(Screenutils.getScreenWidth(mActivity) / 2, Screenutils.getScreenWidth(mActivity) / 2);
        imageView.setLayoutParams(layoutParams);  //设置图片宽高
        imageView.setAdjustViewBounds(true);
        imageView.setImageResource(R.drawable.shop_1); //图片资源

        ImageView imageView2 = new ImageView(mActivity);
        ViewGroup.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(Screenutils.getScreenWidth(mActivity) / 2, Screenutils.getScreenWidth(mActivity) / 2);
        imageView2.setLayoutParams(layoutParams2);  //设置图片宽高
        imageView2.setAdjustViewBounds(true);
        imageView2.setImageResource(R.drawable.shop_1); //图片资源

        ImageView imageView3 = new ImageView(mActivity);
        ViewGroup.LayoutParams layoutParams3 = new LinearLayout.LayoutParams(Screenutils.getScreenWidth(mActivity) / 2, Screenutils.getScreenWidth(mActivity) / 2);
        imageView3.setLayoutParams(layoutParams3);  //设置图片宽高
        imageView3.setAdjustViewBounds(true);
        imageView3.setImageResource(R.drawable.shop_1); //图片资源

        ImageView imageView4 = new ImageView(mActivity);
        ViewGroup.LayoutParams layoutParams4 = new LinearLayout.LayoutParams(Screenutils.getScreenWidth(mActivity) / 2, Screenutils.getScreenWidth(mActivity) / 2);
        imageView4.setLayoutParams(layoutParams4);  //设置图片宽高
        imageView4.setAdjustViewBounds(true);
        imageView4.setImageResource(R.drawable.shop_1); //图片资源

        adviceShopContainer.addView(imageView);
        adviceShopContainer.addView(imageView2);
        adviceShopContainer.addView(imageView3);
        adviceShopContainer.addView(imageView4);
    }

    @Subscribe
    public void onEventMainThread(EventPoiAddress event) {
        leftText.setText(event.getAddress());
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    private void checkRed() {
        NetTool.getApi().getbonus(NetTool.newParams()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<GetBoundsResponse>>() {
                    @Override
                    public void onData(BaseResponse<GetBoundsResponse> value) {
                        Log.i(TAG, "onData: msg=" + value.msg + " getCode=" + value.getCode());
                        if (value.getCode() == 0 && value.getData() != null) {
                            if (value.getData().getBonus_num() == 1) {
                                DialogManger.showRedDialog(getFragmentManager(), value.getData().getBonus_list().get(0));
                            } else if (value.getData().getBonus_num() != 0) {
                                DialogManger.showRedListDialog(mActivity, value.getData());
                            }
                        }
                    }
                });
    }

    public void startAnim(View v, View vs) {
        ImageView view = v.findViewById(R.id.product_img);
        ImageView viewCopy = new ImageView(mActivity);
        Drawable drawable = zoomDrawable(view.getDrawable(), 200, 200);
        viewCopy.setImageDrawable(drawable);
        AniManager mAniManager = new AniManager();
        int[] end_location = new int[2];
        int[] start_location = new int[2];
        vs.getLocationInWindow(start_location);// 获取购买按钮的在屏幕的X、Y坐标（动画开始的坐标）
        car.getLocationInWindow(end_location);// 这是用来存储动画结束位置，也就是购物车图标的X、Y坐标
        //buyImg = new ImageView(this);// buyImg是动画的图片
        //buyImg.setImageResource(R.mipmap.sign);// 设置buyImg的图片
        //mAniManager.setTime(5500);//自定义时间
        mAniManager.setAnim(mActivity, viewCopy, start_location, end_location);// 开始执行动画

        mAniManager.setOnAnimListener(new AniManager.AnimListener() {
            @Override
            public void setAnimBegin(AniManager a) {
                //动画开始时的监听
            }

            @Override
            public void setAnimEnd(AniManager a) {
                //动画结束后的监听
                ToastUtil.showToast("结束");
                carNum.setBadgeNumber(++carnum);
            }
        });
    }

    @Override
    public void showLoadingProgress() {
        //super.showLoadingProgress();
        if (showLoadingCount == 0) {
            DialogManger.showLoadingProgress(getFragmentManager(), "加载中...");
        }
        showLoadingCount++;
        LogUtil.d("show:" + showLoadingCount);
    }

    @Override
    public void dismissLoadingProgress() {
        //super.dismissLoadingProgress();
        showLoadingCount--;
        if (showLoadingCount <= 0) {
            DialogManger.dismissLoadingProgress();
        }
        LogUtil.d("show:" + showLoadingCount);
    }

    private Bitmap changeBitmapSize(Bitmap bitmap, int w, int h) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        //设置想要的大小
        int newWidth = w;
        int newHeight = h;

        //计算压缩的比率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        //获取想要缩放的matrix
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        //获取新的bitmap
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        bitmap.getWidth();
        bitmap.getHeight();
        return bitmap;
    }

    private Drawable zoomDrawable(Drawable drawable, int w, int h) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap oldbmp = drawableToBitmap(drawable);
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) w / width);
        float scaleHeight = ((float) h / height);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height,
                matrix, true);
        return new BitmapDrawable(null, newbmp);
    }

    private Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }
}
